package com.jp.knowledge.activity;

import android.content.Context;
import android.view.View;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.google.gson.JsonObject;
import com.jiayen.cache.FileCacheManager;
import com.jiayen.util.ToasUtil;
import com.jp.knowledge.R;
import com.jp.knowledge.comm.SlidingActivity;
import com.jp.knowledge.command.Command;
import com.jp.knowledge.command.CommandInvoker;
import com.jp.knowledge.command.CommandReceiver;
import com.jp.knowledge.fragment.JobKnowledgeDataFragment;
import com.jp.knowledge.fragment.PositonToolsDataFragment;
import com.jp.knowledge.http.HttpHelper;
import com.jp.knowledge.model.FoundBanner;
import com.jp.knowledge.model.IModel;
import com.jp.knowledge.model.PositionKnowlegeMode;
import com.jp.knowledge.util.ResultSubscriber;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.listener.OnBannerListener;
import com.youth.banner.loader.ImageLoader;

import org.xutils.common.util.DensityUtil;
import org.xutils.view.annotation.ViewInject;

import java.util.ArrayList;
import java.util.List;

import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by 528787067@qq.com on 2017/7/13.
 */

public class PositionToolsActivity extends SlidingActivity implements ResultSubscriber.OnResultListener, View.OnClickListener {

	private static final int GET_BANNER_CODE = 0x01;
	private static final int GET_TOOLS_LIST_CODE = 0x02;

	@ViewInject(R.id.banner_view)
	private Banner bannerView;

	private PositonToolsDataFragment fragment;
	private PositionKnowlegeMode toolsListData;

	private List<com.jp.knowledge.model.Banner> banners;
	private String bannerCachePath;
	private String toolsListCachePath;
	private FileCacheManager cacheManager;

	@Override
	protected int getResourceId() {
		return R.layout.activity_position_tools;
	}

	@Override
	protected void init() {
		banners = new ArrayList<>();
		bannerCachePath = mContext.getCacheDir() + "/positionToolsBannerData.dat";
		toolsListCachePath = mContext.getCacheDir() + "/positionToolsListData.dat";
		cacheManager = new FileCacheManager();

		topName.setText("岗位工具");
		leftIcon.setImageResource(R.mipmap.arrow_white_left);
		leftIcon.setOnClickListener(this);
		rightIcon.setOnClickListener(this);
		rightIcon.setVisibility(View.GONE);

		bannerView.getLayoutParams().height = (int) (DensityUtil.getScreenWidth() * 302f / 922f + 0.5f);
		bannerView.setBannerStyle(BannerConfig.CIRCLE_INDICATOR);
		bannerView.setIndicatorGravity(BannerConfig.CENTER);
		bannerView.setImageLoader(new ImageLoader(){
			@Override
			public void displayImage(Context context, Object path, ImageView imageView) {
				String imagePath = ((com.jp.knowledge.model.Banner)path).getSrc();
				if("R.mipmap.imaging".equals(imagePath))
					imageView.setImageResource(R.mipmap.imaging);
				else
					Glide.with(mContext).load(imagePath).error(R.mipmap.morentutouxiang).into(imageView);
			}
		});
		bannerView.setOnBannerListener(new OnBannerListener() {
			@Override
			public void OnBannerClick(int position) {
				com.jp.knowledge.model.Banner banner = banners.get(position);
				CommandReceiver receiver = new CommandReceiver.Builder(mContext)
						.withCompanyId(banner.getCommpanyId())
						.withRecordId(banner.getRecordId()).build();
				Command command = Command.create(banner.getCommand(), receiver);
				CommandInvoker.executeCommand(command);
			}
		});

		readToolsListData();
		readBannerCache();
	}

	private void readToolsListData(){
		Observable.create(new Observable.OnSubscribe<PositionKnowlegeMode>() {
			@Override
			public void call(Subscriber<? super PositionKnowlegeMode> subscriber) {
				PositionKnowlegeMode data = (PositionKnowlegeMode) cacheManager.readObject(toolsListCachePath);
				subscriber.onNext(data);
				subscriber.onCompleted();
			}
		}).subscribeOn(Schedulers.io())
		.observeOn(AndroidSchedulers.mainThread())
		.subscribe(new Subscriber<PositionKnowlegeMode>() {
			@Override
			public void onCompleted() {
				getToolsListData();
			}
			@Override
			public void onError(Throwable e) {
				onCompleted();
			}
			@Override
			public void onNext(PositionKnowlegeMode data) {
				setToolsData(data);
			}
		});
	}

	private void readBannerCache(){
		Observable.create(new Observable.OnSubscribe<FoundBanner>() {
			@Override
			public void call(Subscriber<? super FoundBanner> subscriber) {
				FoundBanner appData = (FoundBanner) cacheManager.readObject(bannerCachePath);
				subscriber.onNext(appData);
				subscriber.onCompleted();
			}
		}).subscribeOn(Schedulers.io())
		.observeOn(AndroidSchedulers.mainThread())
		.subscribe(new Subscriber<FoundBanner>() {
			@Override
			public void onCompleted() {
				getBannerData();
			}
			@Override
			public void onError(Throwable e) {
				onCompleted();
			}
			@Override
			public void onNext(FoundBanner data) {
				setBannerData(data);
			}
		});
	}

	private void saveCache(final Object data, final String path){
		new Thread(new Runnable() {
			@Override
			public void run() {
				cacheManager.wirteObject(data, path);
			}
		}).start();
	}

	private void setBannerData(FoundBanner data){
		banners.clear();
		if(data == null || data.getBanner() == null || data.getBanner().size() == 0) {
			com.jp.knowledge.model.Banner banner = new com.jp.knowledge.model.Banner();
			banner.setSrc("R.mipmap.imaging");
			banners.add(banner);
			bannerView.update(banners);
		} else {
			banners.addAll(data.getBanner());
			bannerView.update(banners);
		}
	}

	private void setToolsData(PositionKnowlegeMode model){
		toolsListData = model;
		if(toolsListData != null) {			// 屏蔽掉权限管理
			toolsListData.setState(1);
			toolsListData.setViewPermit(0);
		}
		if(fragment == null){
			fragment = PositonToolsDataFragment.newInstance(toolsListData);
			getSupportFragmentManager()
					.beginTransaction()
					.replace(R.id.tools_content_view, fragment)
					.commit();
		} else{
			fragment.updateView(this.toolsListData);
		}
	}

	private void getBannerData(){
		JsonObject param = new JsonObject();
		param.addProperty("action", 3);
		HttpHelper.getInstance(mContext).discoverData(param, GET_BANNER_CODE, this);
	}

	private void getToolsListData(){
		JsonObject param = new JsonObject();
		param.addProperty("id", "c207e713-63b2-9da1-28cf-b22eb4ef8472");
		HttpHelper.getInstance(mContext).skillNavList(param, GET_TOOLS_LIST_CODE, this);
	}

	@Override
	public void onStart(int requestType) {}
	@Override
	public void onCompleted(int requestType) {}
	@Override
	public void onError(int requestType) {
		onCompleted(requestType);
	}
	@Override
	public void onNext(IModel data, int requestType) {
		if(data.getErrcode() != 0){
			ToasUtil.toast(mContext, data.getMessage());
			onError(requestType);
		} else if(requestType == GET_BANNER_CODE){
			FoundBanner foundBanner = data.getEntity(FoundBanner.class);
			setBannerData(foundBanner);
			saveCache(foundBanner, bannerCachePath);
		} else if(requestType == GET_TOOLS_LIST_CODE){
			List<PositionKnowlegeMode> positionKnowlegeModes = data.getList(PositionKnowlegeMode.class);
			if(positionKnowlegeModes != null && positionKnowlegeModes.size() > 0) {
				setToolsData(positionKnowlegeModes.get(0));
			} else{
				setToolsData(null);
			}
			saveCache(toolsListData, toolsListCachePath);
		}
	}

	@Override
	public void onClick(View v) {
		if(v == leftIcon){
			onBackPressed();
		} else if(v == rightIcon){
			SearchSimpleActivity.gotoSearch(mContext, 25, -1, null, false);
		}
	}
}
